import Vue from 'vue'
import VueRouter from 'vue-router'
import {findAsyncRouter} from '@/api/asyncRouter'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect:'/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  }
]

const router = new VueRouter({
  routes
})

var fist = true; //用来获取后台拿到的路由
router.beforeEach((to, from, next) => {
  let reouterArray = [];
    if (fist) { //不加这个判断，路由会陷入死循环
      fist = false;
      findAsyncRouter().then(res=>{
        console.log(res.data.data)
        reouterArray = res.data.data
        const accessRoutes = getAsyncRoutes(reouterArray);
        console.log(JSON.stringify(accessRoutes))
        router.addRoute(accessRoutes)
           // router.addRoute(reouterArray) //动态添加路由
      // 等待路由添加完成在跳转
      next({ ...to, replace: true })
      console.log(router)
      })
    }else {
      next()
    }
  


});

export function getAsyncRoutes(routes) {
  const res = {path: "",name: "",component: "",children: [],redirect: ""}
  // 定义路由中需要的自定名
  const keys = ['path', 'name', 'children', 'redirect', 'meta', 'hidden']
  // 遍历路由数组去重组可用的路由
  console.log(routes)
  routes.forEach(item => {
    let lsAry = [];
    item.children.forEach((val,j) => {
      lsAry.push({
        path: val.path,
        name: val.name,
        component: () => import(`../views/${val.component}`),
      })
    })
    res.path = item.path;
    res.name = item.name;
    res.component = () => import(`../views/Main`);
    res.redirect = item.redirect;
    res.children = lsAry
  })
 
  // 返回处理好且可用的路由数组
  return res
}

export default router
